<template>
  <div id="PictureManagePage">
    <a-card title="图片管理" class="card-container">
      <a-flex justify="end" style="margin-bottom: 16px">
        <a-button type="primary" href="/add_picture" target="_blank"> 创建图片 </a-button>
        <a-button
          type="primary"
          href="/add_picture/batch"
          target="_blank"
          ghost
          style="margin-left: 8px"
        >
          批量创建图片
        </a-button>
        <a-button
          type="primary"
          href="/add_picture/text_to_image"
          target="_blank"
          shape="round"
          ghost
          style="
            margin-left: 8px;
            margin-bottom: 8px;
            padding: 10px 20px;
            font-size: 16px;
            font-weight: bold;
            background: linear-gradient(135deg, #4facfe, #00f2fe);
            border: none;
            color: white;
          "
        >
          <template #icon>
            <img
              src="https://cdn-icons-png.flaticon.com/512/1828/1828884.png"
              alt="AI"
              width="10"
              style="margin-right: 5px"
            />
          </template>
          AI 文字生成图片
        </a-button>
      </a-flex>

      <!-- 搜索栏 -->
      <a-form layout="inline" :model="searchParams" @finish="doSearch">
        <a-form-item label="关键词" name="searchText">
          <a-input
            v-model:value="searchParams.searchText"
            placeholder="从名称和简介搜索"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="类型" name="category">
          <a-input v-model:value="searchParams.category" placeholder="请输入类型" allow-clear />
        </a-form-item>
        <a-form-item label="标签" name="tags">
          <a-select
            v-model:value="searchParams.tags"
            mode="tags"
            placeholder="请输入标签"
            style="min-width: 180px"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="审核状态" name="reviewStatus">
          <a-select
            v-model:value="searchParams.reviewStatus"
            :options="PIC_REVIEW_STATUS_OPTIONS"
            placeholder="请输入审核状态"
            style="min-width: 180px"
            allow-clear
          />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit">搜索</a-button>
        </a-form-item>
      </a-form>

      <!-- 表格列表 -->
      <a-table
        :columns="columns"
        :data-source="dataList"
        :pagination="pagination"
        @change="doTabelChange"
        class="custom-table"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'url'">
            <a-image :src="record.url" :width="80" class="avatar-image" />
          </template>
          <!-- 标签 -->
          <template v-if="column.dataIndex === 'tags'">
            <a-space wrap>
              <a-tag
                v-for="tag in JSON.parse(record.tags || '[]')"
                :key="tag"
                :color="getTagColor(tag)"
                class="custom-tag"
              >
                <template #icon>
                  <TagOutlined />
                </template>
                {{ tag }}
              </a-tag>
            </a-space>
          </template>
          <template v-if="column.dataIndex === 'picInfo'">
            <a-space direction="vertical" size="small">
              <span><strong>格式：</strong>{{ record.picFormat }}</span>
              <span><strong>宽高：</strong>{{ record.picWidth }} × {{ record.picHeight }}</span>
              <span><strong>宽高比：</strong>{{ record.picScale }}</span>
              <span
                ><strong>大小：</strong>
                <span style="color: #1890ff; font-weight: 600"
                  >{{ (record.picSize / 1024).toFixed(2) }} KB</span
                >
              </span>
            </a-space>
          </template>

          <template v-if="column.dataIndex === 'reviewMessage'">
            <a-space direction="vertical" size="small">
              <span
                ><strong>状态：</strong>
                <a-tag :color="getReviewStatusColor(record.reviewStatus)">
                  {{ PIC_REVIEW_STATUS_MAP[record.reviewStatus] }}
                </a-tag>
              </span>
              <span><strong>信息：</strong>{{ record.reviewMessage || '暂无' }}</span>
              <span><strong>审核人：</strong>{{ record.reviewerId || '系统' }}</span>
            </a-space>
          </template>

          <template v-if="column.dataIndex === 'createTime'">
            <a-space>
              <ClockCircleOutlined style="color: #1890ff" />
              <span>{{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
            </a-space>
          </template>

          <template v-else-if="column.dataIndex === 'editTime'">
            <a-space>
              <EditOutlined style="color: #52c41a" />
              <span>{{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
            </a-space>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space size="small" wrap>
              <!-- 通过按钮 -->
              <a-button
                v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.PASS"
                type="primary"
                size="small"
                ghost
                @click="handleReview(record, PIC_REVIEW_STATUS_ENUM.PASS)"
              >
                <template #icon>
                  <CheckOutlined />
                </template>
                通过
              </a-button>

              <!-- 拒绝按钮 -->
              <a-button
                v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.REJECT"
                type="primary"
                danger
                size="small"
                ghost
                @click="handleReview(record, PIC_REVIEW_STATUS_ENUM.REJECT)"
              >
                <template #icon>
                  <CloseOutlined />
                </template>
                拒绝
              </a-button>

              <!-- 编辑按钮 -->
              <a-button
                type="dashed"
                size="small"
                :href="`/add_picture?id=${record.id}`"
                target="_blank"
              >
                <template #icon>
                  <EditOutlined />
                </template>
                编辑
              </a-button>

              <!-- 删除按钮 -->
              <a-button
                type="default"
                danger
                size="small"
                class="delete-button"
                @click="doDelete(record.id)"
              >
                <template #icon>
                  <DeleteOutlined />
                </template>
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import {
  deletePictureUsingPost,
  doPictureReviewUsingPost,
  listPictureByPageUsingPost,
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  PIC_REVIEW_STATUS_ENUM,
  PIC_REVIEW_STATUS_MAP,
  PIC_REVIEW_STATUS_OPTIONS,
} from '../../constants/picture.ts'
import { TagOutlined } from '@ant-design/icons-vue'

import {
  ClockCircleOutlined,
  EditOutlined,
  CheckOutlined,
  CloseOutlined,
  DeleteOutlined,
} from '@ant-design/icons-vue'

// 审核状态颜色
const getReviewStatusColor = (status) => {
  switch (status) {
    case 'PASS':
      return 'green'
    case 'REJECT':
      return 'red'
    default:
      return 'blue'
  }
}

// 随机颜色分配函数
const getTagColor = (tag) => {
  const colors = ['blue', 'green', 'volcano', 'gold', 'purple', 'red', 'cyan', 'magenta', 'lime']
  let hash = 0
  for (let i = 0; i < tag.length; i++) {
    hash = tag.charCodeAt(i) + ((hash << 5) - hash)
  }
  return colors[Math.abs(hash) % colors.length] // 基于 tag 计算颜色
}

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '图片',
    dataIndex: 'url',
  },
  {
    title: '名称',
    dataIndex: 'name',
  },
  {
    title: '简介',
    dataIndex: 'introduction',
    ellipsis: true,
  },
  {
    title: '类型',
    dataIndex: 'category',
  },
  {
    title: '标签',
    dataIndex: 'tags',
  },
  {
    title: '图片信息',
    dataIndex: 'picInfo',
  },
  {
    title: '用户 id',
    dataIndex: 'userId',
    width: 80,
  },
  {
    title: '审核信息',
    dataIndex: 'reviewMessage',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

const dataList = ref<API.Picture[]>([])
const total = ref(0)

const searchParams = reactive<API.PictureQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'descend',
})

const pagination = computed(() => ({
  current: searchParams.current ?? 1,
  pageSize: searchParams.pageSize ?? 10,
  total: total.value,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条`,
}))

const doTabelChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

const fetchData = async () => {
  const res = await listPictureByPageUsingPost({
    nullSpaceId:true,
    ...searchParams })
  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

const doSearch = () => {
  searchParams.current = 1
  fetchData()
}

import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { Modal } from 'ant-design-vue'
import { createVNode } from 'vue'

const doDelete = async (id: string) => {
  if (!id) return
  Modal.confirm({
    title: '⚠️ 确定要删除这张图片吗？',
    content: '删除后无法恢复，请谨慎操作！',
    icon: createVNode(ExclamationCircleOutlined, { style: 'color: red' }),
    centered: true,
    okText: '删除',
    okType: 'danger',
    cancelText: '取消',
    okButtonProps: {
      style: { backgroundColor: '#ff4d4f', borderColor: '#ff4d4f', color: '#fff' }, // 确保文字是白色
    },
    onOk: async () => {
      const res = await deletePictureUsingPost({ id })
      if (res.data.code === 0) {
        message.success('✅ 删除成功')
        fetchData()
      } else {
        message.error('❌ 删除失败')
      }
    },
  })
}

onMounted(() => {
  fetchData()
})

const handleReview = async (record: API.Picture, reviewStatus: number) => {
  const isReject = reviewStatus === PIC_REVIEW_STATUS_ENUM.REJECT
  Modal.confirm({
    title: isReject ? '❌ 确认拒绝该图片？' : '✅ 确认通过该图片？',
    content: isReject
      ? '请确认该图片不符合审核要求，拒绝后无法撤销。'
      : '该图片将被标记为审核通过。',
    icon: createVNode(ExclamationCircleOutlined, { style: `color: ${isReject ? 'red' : 'green'}` }),
    centered: true,
    okText: isReject ? '拒绝' : '通过',
    okType: isReject ? 'danger' : 'primary',
    cancelText: '取消',
    okButtonProps: {
      style: isReject
        ? { backgroundColor: '#ff4d4f', borderColor: '#ff4d4f', color: '#fff' } // 确保拒绝按钮文字是白色
        : { backgroundColor: '#52c41a', borderColor: '#52c41a', color: '#fff' }, // 通过按钮绿色
    },
    onOk: async () => {
      const reviewMessage = isReject ? '管理员操作拒绝' : '管理员操作通过'
      const res = await doPictureReviewUsingPost({
        id: record.id,
        reviewStatus,
        reviewMessage,
      })
      if (res.data.code === 0) {
        message.success(isReject ? '❌ 审核已拒绝' : '✅ 审核已通过')
        fetchData()
      } else {
        message.error('审核操作失败，' + res.data.message)
      }
    },
  })
}
</script>

<style scoped>
#PictureManagePage {
  padding: 24px;
  background: #f5f5f5;
}

.card-container {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background: #fff;
  padding: 20px;
}

.search-bar {
  margin-bottom: 16px;
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.custom-table :deep(.ant-table-tbody > tr:hover) {
  background: #e6f7ff !important;
  transition: all 0.3s ease;
  transform: scale(1.02); /* 轻微放大 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15); /* 添加阴影 */
}

.avatar-image {
  border-radius: 50%;
  transition: transform 0.3s ease-in-out;
}

.avatar-image:hover {
  transform: scale(1.1);
}

.delete-button {
  transition: all 0.3s ease;
}

.delete-button:hover {
  background-color: red !important;
  color: white !important;
  transform: scale(1.05);
}

.delete-button {
  border: 1px solid red;
  transition: all 0.3s ease-in-out;
}

.delete-button:hover {
  background-color: red !important;
  color: white !important;
  transform: scale(1.05);
}

/* 标签美化 */
.custom-tag {
  font-size: 14px;
  font-weight: 500;
  border-radius: 8px;
  padding: 4px 10px;
  transition: all 0.3s ease-in-out;
}

/* 悬停时放大 */
.custom-tag:hover {
  transform: scale(1.1);
}
</style>
